from qiniu import Auth, put_file_v2, etag
import qiniu.config

# 打开并读取文本文件
file_path = 'qiniuKey.txt'  # 文件路径，请根据实际情况修改

access_key = ''
secret_key = ''

try:
    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            print(line.strip())  # 使用 strip() 去除行末的换行符
            if line.startswith('ak:'):
                access_key = line.replace('ak:', '', 1)
            elif line.startswith('sk:'):
                secret_key = line.replace('sk:', '', 1)
except FileNotFoundError:
    print(f"文件 {file_path} 未找到，请检查路径是否正确。")
except Exception as e:
    print(f"读取文件时发生错误：{e}")

print( "access_key: " + access_key)
print( "secret_key: " + secret_key)

q = Auth(access_key, secret_key)
#构建鉴权对象
#要上传的空间
bucket_name = 'sid2656'
#上传后保存的文件名
key = 'test.jpg'
#生成上传 Token，可以指定过期时间等
token = q.upload_token(bucket_name, key, 3600)
print( "token: " + token)
#要上传文件的本地路径
localfile = '/Users/yesong/IdeaProjects/blogPics/tmp/IMG_5895.jpg'
ret, info = put_file_v2(token, key, localfile, version='v2')
print(ret)
print(info)
assert ret['key'] == key
assert ret['hash'] == etag(localfile)